package com.devunion.bogdan.view.editors;

import org.apache.log4j.Logger;

import javax.swing.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.awt.*;

import com.devunion.bogdan.model.project.Annotation;

/**
 * User: user
 * Date: 06.02.2003
 * Time: 18:50:26
 */
public class AnnotationManager {
    private Logger log = Logger.getLogger(AnnotationManager.class);

    private static AnnotationManager instance = new AnnotationManager();

    public static AnnotationManager getInstance() {
        return instance;
    }

    /**
     * Contains all components and information about their location
     */
    private Map<Component, ComponentInfo> component2componentInfo = new HashMap<Component, ComponentInfo>();
    private ComponentFactory componentFactory = new ComponentFactory(component2componentInfo);
    private SelectionManager selectionManager = null;

    private AnnotationManager() {
        selectionManager = new SelectionManager(component2componentInfo);
    }

    public void removeComponent(Component c) {
        JComponent parent = (JComponent) c.getParent();

        if (parent != null) {
            parent.remove(c);
            component2componentInfo.remove(c);

            parent.repaint(c.getBounds());
        }
    }

    public Component model2View(Annotation annotation) {
        for (Component component : component2componentInfo.keySet()) {
            AnnotationView view = (AnnotationView) component;

            if (view.getAnnotation() == annotation) {
                return view;
            }
        }

        return null;
    }

    public void removeSelectedComponents() {
        List<Component> selectedComponents = selectionManager.getSelectedComponents();

        log.debug("Number of selected component2componentInfo: " + selectedComponents.size());
        if (selectedComponents.isEmpty()) {
            return;
        }

        JComponent parent = (JComponent) ((Component) selectedComponents.get(0)).getParent();

        for (Component component : selectedComponents) {
            parent.remove(component);
            component2componentInfo.remove(component);

            parent.repaint(component.getBounds());
        }
    }

    public SelectionManager getSelectionManager() {
        return selectionManager;
    }

    public ComponentFactory getComponentFactory() {
        return componentFactory;
    }

    public ComponentInfo getComponentInfo(Component c) {
        return component2componentInfo.get(c);
    }
}
